package com.limi.gridfsop.service.impl;

import com.limi.gridfsop.service.FileService;
import com.limi.gridfsop.utils.ContentTypeUtil;
import com.mongodb.client.gridfs.model.GridFSFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * @author limi
 * @date 2020/04/27
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Override
    public String storeFile(MultipartFile file) {
         try {
             String fileName = file.getOriginalFilename();
             String contentType = fileName.substring(fileName.lastIndexOf(".") + 1);
             ObjectId objectId = gridFsTemplate.store(file.getInputStream(), fileName, contentType);
             return objectId.toString();
         } catch (Exception e) {
             log.error("Store file error: {}", e.getMessage());
         }
        return null;
    }

    @Override
    public void downloadFile(String id) {
        try {
            // 根据id查找文件
            GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));

            // 创建gridFsSource，用于获取流对象
            GridFsResource gridFsResource = gridFsTemplate.getResource(gridFSFile);

            // 获取response及设置
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = servletRequestAttributes.getResponse();
            String fileName = new String(gridFSFile.getFilename().getBytes("GBK"), "ISO-8859-1");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) gridFSFile.getLength());
            response.setContentType(ContentTypeUtil.getContentType(fileName.substring(fileName.lastIndexOf("."))));
            response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");

            // 获取文件流
            ServletOutputStream outputStream = response.getOutputStream();
            // 将输入流转换为输出流
            IOUtils.copy(gridFsResource.getInputStream(), outputStream);

            outputStream.flush();
            outputStream.close();

        } catch (Exception e) {
            log.error("Get file error: {}", e.getMessage());
        }

    }
}
